<?php
declare(strict_types=1);
/**
 * Notes:
 * User: ysian
 * Time: 23:03
 * @return
 */

namespace Ysian\Storage;

use Symfony\Component\Translation\Exception\RuntimeException;
use Ysian\Storage\exception\StorageException;
/**
 * @class Storage
 * @method static array uploadFile(array $config = [])                          上传文件
 * @method static array uploadBase64(string $base64, string $extension = 'png') 上传Base64文件
 * @method static array uploadServerFile(string $file_path)                     上传服务端文件
 */
class Storage
{
    protected static $adapter = ''; //适配器
    protected static $config  = []; //配置项
    # 适配器集合
    protected static $adapterArr = [
        'local'   =>  \Ysian\Storage\adapter\LocalAdapter::class,
        'qos'     =>  \Ysian\Storage\adapter\QiniuAdapter::class,
        'oss'     =>  \Ysian\Storage\adapter\LocalAdapter::class,
        'cos'     =>  \Ysian\Storage\adapter\LocalAdapter::class,
    ];

    public static function __callStatic($name, $arguments)
    {
        # 初始化配置
        if(empty(static::$config)) static::config(...$arguments);

        $result =  static::$adapter->$name();
        static::$config = []; //配置重新初始化
        return $result;
    }


    /**
     * 初始化配置
     * @param string $storage
     * @param array $config
     */
    public static function config(array $config = [])
    {
        # 获取配置文件内容
        $storageConfig  = config('storage');

        # 获取上传类型,以传参为主,没有则取配置文件,文件无默认为local
        $storage = $config['default'] ?? $storageConfig['default'] ?? 'local';

        # 组装config,以传参为主
        $common         = $storageConfig['common'] ?? [];
        $storageConfig  = $storageConfig[$storage] ?? [];
        static::$config = array_merge($common,$storageConfig,$config);

        # 实例化
        if(!isset(self::$adapterArr[$storage])) throw new \RuntimeException('暂不支持'.$storage.'类型上传');
        static::$adapter = new (self::$adapterArr[$storage])(self::$config);
    }
}